// pages/commonPage/foodTicket/foodTicket.js
// pages/index/index.js
var netWork = require('../../../utils/netWork.js');
var api = require('../../../utils/api.js');
var apiCode = require('../../../utils/openApiCode.js');
const log = require('../../../utils/logs.js');
const QR = require('../../../utils/weapp-qrcode.js');
var Base64 = require('../../../utils/base64.js');
import {openLocation,getLocation,getSettingUserLocation} from "../../../utils/wxapi";
const app = getApp();
// var base = new Base64();
var popup = require('../../../utils/popupUtils.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imagesUrl: getApp().globalData.imagesUrl,
        topHeight: 0,
        type: 2,
        ticket: '',
        isVolumeTips:false,
        prizeTypeId:0,//卷类型 16兑换  17买赠
        gotopageIndex:0,//下张显示卷的下标
        flag:false,//是否是浓香分支
        prizeList:[],//上个页面的中奖列表数据
        prevPage:"",//上个页面信息
        item:{},//当前显示的卷信息
        sendType:"",//消息推送进入详情页
        back:true,//返回上个页面
        home:false,//返回首页
        isShowReceivePrize:false,//是否确认领奖弹窗（兑换券显示）
        isShowReceivePrizeMsg:"确定已领取到奖品吗?"//是否确认领奖弹窗显示文字（兑换券显示）
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        //从webview获取用户id返回卷详情页面后记录用户id
        //把缓存中的卷码和type从新赋值并清楚缓存
        if (options.userId) {
            wx.setStorageSync('userId', options.userId);
            if(wx.getStorageSync('sendType')){
                options.type = wx.getStorageSync('sendType');
                options.fticketNo =  wx.getStorageSync('sendFticketNo');
                wx.removeStorageSync('sendFticketNo');
                wx.removeStorageSync('sendType');
            }
        }
        // 用户类型
        if (options.userType) {
            wx.setStorageSync('userType', options.userType);
        }
        //没有用户id暂时判断为用户清了小程序缓存从消息通知进入进webview获取用户id
        //卷码和type记录缓存
        if (wx.getStorageSync('userId') == '' || wx.getStorageSync('userId') == null || wx.getStorageSync('userId') == undefined) {
            if(options.type){
                wx.setStorageSync('sendFticketNo', options.fticketNo);
                wx.setStorageSync('sendType', options.type);
            }
            wx.redirectTo({
              url: '../../webview/webview?intoType=/pages/commonPage/ticket/ticket&type=fullPath'
            })
        }
        console.log("通用页面");
        // this.isLoading(true, "正在加载中...");
        log.info("[index]--->[onLoad]")
        try {
            const {
                SDKVersion = ''
            } = wx.getSystemInfoSync();
            // 获取系统信息
            const that = this;
            wx.getSystemInfo({
                success: function (res) {
                    console.log(res)
                    that.setData({
                        addHeight: (res.screenHeight * res.pixelRatio - 1334) / 6,
                        screenHeight: res.screenHeight - res.statusBarHeight - 50
                    });
                }
            });
            console.log(that.data.addHeight)
            log.info(SDKVersion)
            const compatibility = util.compareVersion(SDKVersion, '2.2.2');
            log.info(compatibility)
            if (compatibility == -1) {
                wx.showModal({
                    content: '您的微信版本过低，请升级后再来吧~',
                    confirmText: '我知道了',
                    showCancel: false
                });
                return;
            }
        } catch (e) {}
        try {
            // 检测是否可以调用getUpdateManager检查更新
            if (!wx.canIUse("getUpdateManager")) return;
            let updateManager = wx.getUpdateManager();
            // 获取全局唯一的版本更新管理器，用于管理小程序更新
            updateManager.onCheckForUpdate(function (res) {
                log.info(res)
                // 监听向微信后台请求检查更新结果事件
                log.info("是否有新版本：" + res.hasUpdate);
                if (res.hasUpdate) {
                    //如果有新版本
                    // 小程序有新版本，会主动触发下载操作
                    updateManager.onUpdateReady(function () {
                        //当新版本下载完成，会进行回调
                        wx.showModal({
                            title: '更新提示',
                            content: '新版本已经准备好，单击确定重启小程序',
                            showCancel: false,
                            success: function (res) {
                                if (res.confirm) {
                                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                                    updateManager.applyUpdate();
                                }
                            }
                        })
                    })
                    // 小程序有新版本，会主动触发下载操作（无需开发者触发）
                    updateManager.onUpdateFailed(function () {
                        //当新版本下载失败，会进行回调
                        wx.showModal({
                            title: '提示',
                            content: '检查到有新版本，但下载失败，请稍后尝试',
                            showCancel: false,
                        })
                    })
                }
            });
        } catch (e) {
            e
        }
        //高度处理
        let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
        this.setData({
            topHeight: topHeight,
            fticketNo: decodeURIComponent(options.fticketNo),

            icon: wx.getStorageSync('productType') == 4 || wx.getStorageSync('productType') == 5 ? 'xinyouranPage/loading_logo' : 'common/loading',
            //   qrcodeBigURL: '', 

        });

        api.judgeNetworkStatus(function (res) {
            if ("none" == res) return;
        })
        this.data.sendType = options.type;
        this.loadTicket();
        if(options.type){
            this.setData({
                back:false,
                home:true
            })
        }else{
            //不是通过消息推送进入详情页走下面方法
            this.data.flag = options.flag;//浓香分支独有参数
            let pages = getCurrentPages(); //当前页面
            this.data.prevPage = pages[pages.length - app.globalData.prevPageNum]; //上一页面
            app.globalData.prevPageNum = app.globalData.prevPageNum+1;
        }

    },

    async loadTicket() {
        this.isLoading(true, "加载中...");
        let productType = wx.getStorageSync('productType');
  
        let error_url = productType == 4 ? '../../xinyouranPage/prompt/prompt' : productType == 1 ? '../../jingdianPage/prompt/prompt' : productType == 2 ? '../../prompt/prompt' : productType == 3 ? '../../ruiPage/prompt/prompt' : '../../xinyouranPage/xinyouranHighPage/prompt/prompt';
        const that = this;
        // let ticketBase64= Base64.encode(this.data.fticketNo).replace("=","");
        let data = {
            fticketNo:Base64.encode(this.data.fticketNo).replace(/=/g,""),
            userId: wx.getStorageSync('userId')
        };
        //地理位置
        let us = await getSettingUserLocation();
        if(us){
            let gl = await getLocation();
            if(gl.errMsg == "getLocation:ok"){
                data.lat = gl.latitude;
                data.lng = gl.longitude;
            }
        }
        netWork.POST_Ticket('coupons/info', {
            data: data,
            success: function (res) {
                // console.log(getApp().globalData.requestGanguoUrl+'?ticketNo=' + Base64.encode(that.data.fticketNo).replace(/=/g,""))
                that.isLoading(false);
                if (res.data.code == undefined) {
                    wx.redirectTo({
                        url: error_url + '?retCode=' + res.data.code + '&retMsg=' + res.data.msg,
                    })
                }
                if (res.data.code == "1001") {
                    //成功，调用查询礼券详情接口
                    if (res.data.data == '' || res.data.data == null) { //礼券为空
                        wx.redirectTo({
                            url: error_url + '?retCode=' + res.data.code + '&retMsg=' + res.data.msg,
                        })
                        return;
                    } else { //成功
                        that.setData({
                            ticket: res.data.data,
                            showAll: res.data.data.exchangeTerminal != null && res.data.data.exchangeTerminal.length > 3 ? false : true,

                            qrcodeBigURL: that.drawImg(getApp().globalData.requestGanguoUrl+'?ticketNo=' + Base64.encode(that.data.fticketNo).replace(/=/g,""))
                        })
                        let buyNames = '';
                        let ticket = res.data.data;
                        if (ticket.buyDetails != null) {
                            for (let i = 0; i < ticket.buyDetails.length; i++) {
                                 //购买商品dataRelation判断是叠加还是或者
                                // 1叠加 2或者
                                buyNames += ticket.buyDetails[i].num+'瓶【'+ticket.buyDetails[i].productName+'】';
                                if (i + 1 != res.data.data.buyDetails.length) {
                                    buyNames += ticket.buyDetails[i].dataRelation == 2?"或者":"叠加";
                                }
                            }
                        }
                        let exChangeNames = '';
                        if (ticket.exchangeDetails != null) {
                            for (let i = 0; i < ticket.exchangeDetails.length; i++) {
                                let data = ticket.exchangeDetails[i];
                                //赠送商品type判断,餐饮卷和精简名称直接显示prizeName文字不做改变
                                //1酒对换券 2餐饮券 3精简名称
                                exChangeNames += (data.type == 2 || data.type == 3)?data.prizeName:data.num+'瓶【'+data.prizeName+'】';
                                if (i + 1 != res.data.data.exchangeDetails.length) {
                                    exChangeNames += ticket.exchangeDetails[i].dataRelation == 2?"或者":"叠加";
                                }
                            }
                        }


                        that.setData({
                            buyNames: buyNames,
                            exChangeNames: exChangeNames
                        })
                        if(that.data.sendType && ticket.status == 8){
                            that.setPrizeStatus(ticket.prizeOrderId);
                        }
                    }
                } else {
                    wx.redirectTo({
                        url: error_url + '?retCode=' + res.data.code + '&retMsg=' + res.data.msg,
                    })

                }
            },
            fail: function () {
                that.isLoading(false);
                wx.redirectTo({
                    url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                })
            }
        })
    },
    isLoading(isLoading, loadingText) {
        this.setData({
            isLoading: isLoading,
            loadingText: loadingText
        })

    },
    //生成二维码
    drawImg: function (ticketNo) {
        var imgData = QR.drawImg(ticketNo, {
            typeNumber: 4,
            errorCorrectLevel: 'M',
            size: 500
        })
        return imgData;
    },
    showAllList() {
        this.setData({
            showAll: true
        })
    },
    handlerGobackClick() {
        if(this.data.sendType){//推送进入小程序点击返回首页
            wx.redirectTo({
                url: "../../scan/scan"
            })
        }else{
            //修改卷状态为13并判断当前卷是否有价值是否需要改变小手状态
            this.setStatus();
            app.globalData.prevPageNum = app.globalData.prevPageNum-1;
            wx.navigateBack({
                delta: 1
            });
        }
    },
    setVolumeStatus(){
        //修改卷的状态为13
        for(let item of this.data.prizeList){
            if(item.fticketNo == this.data.fticketNo){
                this.data.item = item;
                if(item.status != 10 && item.status != 11){
                    item.status = 13;
                }
                break;
            }
        }
        //浓香分支找到下张status等于8的卷信息
        if(this.data.flag){
            for(let i=0;i<this.data.prizeList.length;i++){
                if(this.data.prizeList[i].prizeTypeId==16 || this.data.prizeList[i].prizeTypeId==17){
                    if(this.data.prizeList[i].status == 8){
                        this.setData({
                            prizeTypeId:this.data.prizeList[i].prizeTypeId,
                            isVolumeTips:true,
                            gotopageIndex:i
                        })  
                        break;
                    }
                }
            }
        }
    },
    //把中奖页面卷的按钮状态改为13
    //浓香分支进入详情页this.data.flag是true判断是否改变小手状态
    //其他分支暂时没有这个功能
    setStatus(){
        for(let item of this.data.prizeList){
            if(item.fticketNo == this.data.fticketNo){
                if(item.status != 10 && item.status != 11){
                    item.status = 13;
                }
                this.data.prevPage.setData({ //直接给上移页面赋值
                    prizeList: this.data.prizeList
                });
                if(this.data.flag){
                    wx.setStorageSync('prizeList', this.data.prizeList);
                    if(item.prizeShowAmount != null && item.prizeShowAmount != ""){
                        this.data.prevPage.data.handPrizeId = item.id;
                        popup.setHandFlag(this.data.prevPage);
                    }
                }
                break;
            }
        }
    },
    //关闭卷提示
    closeVolumeTips(){
        this.setData({
            isVolumeTips:false
        })
    },
    //显示下一张卷的数据
    gotopage(){
        let fticketNo = this.data.prizeList[this.data.gotopageIndex].fticketNo;
        let prizeOrderId = this.data.prizeList[this.data.gotopageIndex].prizeOrderId;
        //卷状态改为13立即使用
        netWork.POST('ticketUsed', {
            data: {
                userId: wx.getStorageSync('userId'),
                prizeOrderId: prizeOrderId,
                ticketNo: Base64.encode(fticketNo).replace(/=/g,"")
            },
            success: function (res) {
            },
            fail: function (res) {
            }
        });
        //关闭卷提示
        this.closeVolumeTips();
        //判断是否有价值字段
        //有价值设置小手提示
        if(this.data.item.prizeShowAmount != null && this.data.item.prizeShowAmount != ""){
            this.data.prevPage.data.handPrizeId = this.data.item.id;
            popup.setHandFlag(this.data.prevPage);
        }
        this.data.prizeList = wx.getStorageSync('prizeList');
        //消息通知提示
        wx.requestSubscribeMessage({
            tmplIds: ['KyJMnBXyKJ1nrCQiMfRDCZnT-JLSMVo1cz98jC85cKg', 'mLYNe8uqrdlB28ymi8g70TMXtaZ-Apc2ZIf_6gbudco','WNN9vqU-qSPjlpN8kj8J5OMIbqXKbSkqGN3YvAu_w0A'],
            success(res) {
                wx.navigateTo({
                    url: '../ticket/ticket?fticketNo='+encodeURIComponent(fticketNo)+"&flag=true"
                })
            },
            fail(res) {
                wx.navigateTo({
                    url: '../ticket/ticket?fticketNo='+encodeURIComponent(fticketNo)+"&flag=true"
                })
            }
        })
    },
    onShow(){
        if(!this.data.sendType){//不是通过消息推送进入详情页走下面方法
            this.data.prizeList = this.data.prevPage.data.prizeList;
            this.setVolumeStatus();
        }
        try {
            if (wx.onNeedPrivacyAuthorization) {
                wx.onNeedPrivacyAuthorization(resolve => {
                    this.selectComponent('#privacyPopup').show();//这里是让组件弹窗显示
                    this.selectComponent('#privacyPopup').data.parentPageInfo = this;
                    this.resolvePrivacyAuthorization = resolve
                })
            }
        } catch (error) {
            console.info(error)
        }
    },
    //修改卷状态
    setPrizeStatus(prizeOrderId){
        netWork.POST('ticketUsed', {
            data: {
              userId: wx.getStorageSync('userId'),
              prizeOrderId: prizeOrderId,
              ticketNo: Base64.encode(this.data.fticketNo).replace(/=/g,"")
            },
            success: function (res) {
            },
            fail: function (res) {
            }
        })
    },
    //跳转导航
    navigation(e){
        let item = e.currentTarget.dataset.item;
        if(item.lat && item.lng){
            openLocation(item);
        }
    },
    isShowReceivePrizePopup(){
        this.setData({
            isShowReceivePrize:!this.data.isShowReceivePrize
        })
    },
    receivePrize(){
        this.isShowReceivePrizePopup()
        this.isLoading(true, "加载中...");
        let productType = wx.getStorageSync('productType');
        let error_url = productType == 4 ? '../../xinyouranPage/prompt/prompt' : productType == 1 ? '../../jingdianPage/prompt/prompt' : productType == 2 ? '../../prompt/prompt' : productType == 3 ? '../../ruiPage/prompt/prompt' : '../../xinyouranPage/xinyouranHighPage/prompt/prompt';
        const that = this;
        let data = {
            fticketNo:Base64.encode(this.data.fticketNo).replace(/=/g,""),
            prizeOrderId: this.data.ticket.prizeOrderId
        };
        netWork.POST_Exchange('coupons/exchange/customerDirect', {
            data: data,
            success: function (res) {
                that.isLoading(false);
                if (res.data.code == undefined) {
                    wx.redirectTo({
                        url: error_url + '?retCode=' + res.data.code + '&retMsg=' + res.data.msg,
                    })
                }
                if (res.data.code == "1001") {
                    that.data.ticket.status = '11';
                    that.data.ticket.customerDirect = false;
                    that.setData({
                        ticket:that.data.ticket,
                        showToast:true,
                        showToastText: '核销成功'
                    })
                    setTimeout(() => {
                        that.setData({
                            showToast:false
                        })
                    }, 2000);
                    for(let item of that.data.prizeList){
                        if(item.fticketNo == that.data.fticketNo){
                            item.status = 11;
                            that.data.prevPage.setData({ //直接给上移页面赋值
                                prizeList: that.data.prizeList
                            });
                            break;
                        }
                    }
                } else {
                    wx.redirectTo({
                        url: error_url + '?retCode=' + res.data.code + '&retMsg=' + res.data.msg,
                    })
                }
            },
            fail: function () {
                that.isLoading(false);
                wx.redirectTo({
                    url: error_url + '?retCode=' + apiCode.FAIL.code + '&retMsg=' + apiCode.FAIL.msg,
                })
            }
        })
    }
})